package com.itheima.app.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.*;
import com.itheima.service.db.TestSoulService;
import com.itheima.service.db.UserInfoService;
import com.itheima.vo.*;
import net.sf.jsqlparser.expression.LongValue;
import org.apache.dubbo.config.annotation.Reference;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author Guanxing
 * @date 2021/9/28
 */
@Component
public class TestSoulManager {

    @Reference
    private TestSoulService testSoulService;

    @Reference
    private UserInfoService userInfoService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //测灵魂  测试题
    public List<QuestionnaireVo> findTestSoul() {
        //查询问卷  并且  把试题封装进去  要查 试卷表  试题表  试题选项表
        //存放问卷的集合
        ArrayList<QuestionnaireVo> questionnaireVos = new ArrayList<>();

        //查询出来  问卷
        // List<Questionnaire> questionnaires = questionnaireMapper.selectList(new QueryWrapper<>());
        List<Questionnaire> questionnaires = testSoulService.selectListQuestionnaire();
        List<SoulQuestion> questionLists = null;
        List<SoulQuestionOption> questionOptionList = null;

        if (CollectionUtil.isNotEmpty(questionnaires)) {
            for (Questionnaire questionnaire : questionnaires) {
                QuestionnaireVo questionnaireVo = new QuestionnaireVo();
                questionLists = testSoulService.selectquestionList(questionnaire.getId());
                BeanUtil.copyProperties(questionnaire, questionnaireVo);
                //缺少一个是否锁住
                //根据questionnaire的id 查询锁住的状态

                //查询试卷等级
                String level = testSoulService.findQuestionnaireLevel(questionnaire.getId());
                if (StrUtil.equals(level, "1")) {
                    questionnaireVo.setIsLock(0);
                } else if (StrUtil.equals(level, "2")) {
                    String key = "level" + 1 + "userId" + UserHolder.getId();
                    Boolean aBoolean = stringRedisTemplate.hasKey(key);
                    if (aBoolean) {
                        questionnaireVo.setIsLock(0);
                    } else {
                        questionnaireVo.setIsLock(1);
                    }
                } else if (StrUtil.equals(level, "3")) {
                    String key = "level" + 2 + "userId" + UserHolder.getId();
                    Boolean aBoolean = stringRedisTemplate.hasKey(key);
                    if (aBoolean) {
                        questionnaireVo.setIsLock(0);
                    } else {
                        questionnaireVo.setIsLock(1);
                    }
                }

                if (StrUtil.equals(level, "1")) {
                    String key = "level" + 1 + "userId" + UserHolder.getId();
                    Boolean aBoolean = stringRedisTemplate.hasKey(key);
                    if (aBoolean) {
                        //查询最近的报告的conclusion
                        String conclusion = testSoulService.findLastReportId(UserHolder.getId(), level);
                        if (conclusion != null) {
                            //根据报告的内容查询报告的id
                            String id = testSoulService.findLastReportIdBy(conclusion);
                            if (id != null) {
                                questionnaireVo.setReportId(id);
                            }
                        }
                    } else {

                    }
                } else if (StrUtil.equals(level, "2")) {
                    String key = "level" + 2 + "userId" + UserHolder.getId();
                    Boolean aBoolean = stringRedisTemplate.hasKey(key);
                    if (aBoolean) {
                        //查询最近的报告的conclusion
                        String conclusion = testSoulService.findLastReportId(UserHolder.getId(), level);
                        if (conclusion != null) {
                            //根据报告的内容查询报告的id
                            String id = testSoulService.findLastReportIdBy(conclusion);
                            if (id != null) {
                                questionnaireVo.setReportId(id);
                            }
                        }
                    } else {

                    }
                } else if (StrUtil.equals(level, "3")) {
                    String key = "level" + 3 + "userId" + UserHolder.getId();
                    Boolean aBoolean = stringRedisTemplate.hasKey(key);
                    if (aBoolean) {
                        //查询最近的报告的conclusion
                        String conclusion = testSoulService.findLastReportId(UserHolder.getId(), level);
                        if (conclusion != null) {
                            //根据报告的内容查询报告的id
                            String id = testSoulService.findLastReportIdBy(conclusion);
                            if (id != null) {
                                questionnaireVo.setReportId(id);
                            }
                        }
                    } else {

                    }
                }


                //存放试题的集合
                ArrayList<SoulQuestionVo> soulQuestionVos = new ArrayList<>();
                //关于试题的问题和答案封装完成
                if (CollectionUtil.isNotEmpty(questionLists)) {
                    for (SoulQuestion question : questionLists) {
                        SoulQuestionVo soulQuestionVo = new SoulQuestionVo();
                        BeanUtil.copyProperties(question, soulQuestionVo);

                        //查询出来的关于选项的集合（封装完毕）
                        questionOptionList = testSoulService.selectQuestionOptionList(question.getId());
                        //问题选项的集合
                        ArrayList<SoulQuestionOptionVo> soulQuestionOptionVos = new ArrayList<>();

                        if (CollectionUtil.isNotEmpty(questionOptionList)) {
                            for (SoulQuestionOption soulQuestionOption : questionOptionList) {
                                //每个问题的选项
                                SoulQuestionOptionVo soulQuestionOptionVo = new SoulQuestionOptionVo();
                                soulQuestionOptionVo.setId(soulQuestionOption.getId().toString());
                                soulQuestionOptionVo.setOption(soulQuestionOption.getContent());
                                soulQuestionOptionVos.add(soulQuestionOptionVo);
                            }
                        }
                        soulQuestionVo.setOptions(soulQuestionOptionVos);

                        soulQuestionVos.add(soulQuestionVo);
                    }

                }
                questionnaireVo.setQuestions(soulQuestionVos);
                questionnaireVos.add(questionnaireVo);
            }
            return questionnaireVos;
        }
        return null;

    }

    //测灵魂 提交问卷
    public String pushTest(List<SoulPush> answers1) {
        if (CollectionUtil.isNotEmpty(answers1)) {
            Integer fenshu = 0;
            //根据答案的id查询   是那套试卷
            SoulPush soulPush1 = answers1.get(0);
            Long questionnaireId = testSoulService.findQuestionnaireId(soulPush1.getQuestionId());
            //查询试卷等级
            String level = testSoulService.findQuestionnaireLevel(questionnaireId);
            String key = "level" + level + "userId" + UserHolder.getId();
            stringRedisTemplate.opsForValue().set(key, level);

            for (SoulPush soulPush : answers1) {
                String questionId = soulPush.getQuestionId();//试题编号
                String optionId = soulPush.getOptionId();//选项编号

                fenshu += testSoulService.findFenShu(questionId, optionId);
            }

            //调用方法保存到redis是否解锁试卷

            //根据分数范围返回对应的报告id
            return testSoulService.findReportId(fenshu);
        }

        //返回报告的id
        return null;
    }

    //根据报告id  查询报告
    public TestSoulResultVo findReport(String id) {
        //创建一个对象  把报告结果存储进去
        QuestionnaireReport questionnaireReport = new QuestionnaireReport();
        //根据报告id  查询报告   获得了报告
        QuestionnaireResult questionnaireResult = testSoulService.findReportById(id);
        //封装返回对象
        TestSoulResultVo testSoulResultVo = new TestSoulResultVo();
        testSoulResultVo.setConclusion(questionnaireResult.getContent());
        testSoulResultVo.setCover(questionnaireResult.getCover());
        //保存QuestionnaireReport
        questionnaireReport.setUserId(UserHolder.getId());
        questionnaireReport.setConclusion(questionnaireResult.getContent());
        questionnaireReport.setCover(questionnaireResult.getCover());
        //赋值报告等级
        //查询redis
        String key1 = "level" + 1 + "userId" + UserHolder.getId();
        String s = stringRedisTemplate.opsForValue().get(key1);
        if (s != null) {
            questionnaireReport.setLevel(s);
        }
        String key2 = "level" + 2 + "userId" + UserHolder.getId();
        String s2 = stringRedisTemplate.opsForValue().get(key2);
        if (s2 != null) {
            questionnaireReport.setLevel(s2);
        }
        String key3 = "level" + 3 + "userId" + UserHolder.getId();
        String s3 = stringRedisTemplate.opsForValue().get(key3);
        if (s3 != null) {
            questionnaireReport.setLevel(s3);
        }

        //封装dimensions
        ArrayList<Dimensions> dimensions = new ArrayList<>();

        Dimensions dimensions1 = new Dimensions();
        dimensions1.setKey("extroversion");
        dimensions1.setValue(RandomUtil.randomInt(30, 100) + "%");
        questionnaireReport.setExtroversion(dimensions1.getValue());
        dimensions.add(dimensions1);
        Dimensions dimensions2 = new Dimensions();
        dimensions2.setKey("judgement");
        dimensions2.setValue(RandomUtil.randomInt(30, 100) + "%");
        questionnaireReport.setJudgement(dimensions2.getValue());
        dimensions.add(dimensions2);
        Dimensions dimensions3 = new Dimensions();
        dimensions3.setKey("abstraction");
        dimensions3.setValue(RandomUtil.randomInt(30, 100) + "%");
        questionnaireReport.setAbstraction(dimensions3.getValue());
        dimensions.add(dimensions3);
        Dimensions dimensions4 = new Dimensions();
        dimensions4.setKey("rationality");
        dimensions4.setValue(RandomUtil.randomInt(30, 100) + "%");
        questionnaireReport.setRationality(dimensions4.getValue());
        dimensions.add(dimensions4);
        testSoulResultVo.setDimensions(dimensions);
        //保存历史报告
        testSoulService.saveLastReport(questionnaireReport);
        ArrayList<SimilarYou> similarYous = new ArrayList<>();
        //查询报告表中   类型相同的人的id
        List<Long> userIds = testSoulService.findUserIdByConclusion(questionnaireResult.getContent());
        if (CollectionUtil.isNotEmpty(userIds)) {
            for (Long userId : userIds) {
                SimilarYou similarYou = new SimilarYou();
                //根据userid查询user
                UserInfo userInfo = userInfoService.findById(userId);
                similarYou.setId(userId);
                similarYou.setAvatar(userInfo.getAvatar());
                similarYous.add(similarYou);
            }
        } else {
            SimilarYou similarYou = new SimilarYou();
            //根据userid查询user
            UserInfo userInfo = userInfoService.findById(UserHolder.getId());
            similarYou.setId(UserHolder.getId());
            similarYou.setAvatar(userInfo.getAvatar());
            similarYous.add(similarYou);
        }
        testSoulResultVo.setSimilarYou(similarYous);

        return testSoulResultVo;
    }
}
